package com.hdl.school.service;

import android.app.ActivityManager;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;

import com.hdl.school.schoolcontroller.MainActivity;

import java.util.ArrayList;

public class CheckAppAliveService extends Service {

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        if(!isActivityRunning(MainActivity.class.getName())){
            final Intent intent1 = getPackageManager().getLaunchIntentForPackage(getPackageName());
            intent1.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(intent1);
        }
        return super.onStartCommand(intent, flags, startId);
    }

    private  boolean isActivityRunning(String activityName) {
        if (("").equals(activityName) || activityName == null)
            return false;
        ActivityManager myManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
        ArrayList<ActivityManager.RunningTaskInfo> runningTask = (ArrayList<ActivityManager.RunningTaskInfo>) myManager
                .getRunningTasks(30);
        for (int i = 0; i < runningTask.size(); i++) {
            if (runningTask.get(i).topActivity.getClassName().toString()
                    .equals(activityName)) {
                return true;
            }
            if (runningTask.get(i).baseActivity.getClassName().toString()
                    .equals(activityName)) {
                return true;
            }
        }
        return false;
    }

}